﻿using Playnite.SDK.Models;
using Playnite.SDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImportExporter.ImportAttributes
{
    public static class ImportSources
    {
        public static void DoImportSources(IPlayniteAPI PlayniteApi, Game game, List<GameSource> importedSourceList)
        {
            List<GameSource> existedSourceList = PlayniteApi.Database.Sources.ToList();

            // 在imported中根据Id找Name（这个是一定能找到的）
            List<GameSource> spcificationExistsSourceList = importedSourceList.Where<GameSource>(item =>
            {
                return game.SourceId == item.Id;
            }).ToList();
            // 在existed中根据Name找Id（这个不一定能找到，imported来的可能是新的）
            game.SourceId = Guid.Empty;
            foreach (GameSource source in spcificationExistsSourceList)
            {
                List<GameSource> foundList = existedSourceList.FindAll(p => p.Name.Trim().Equals(source.Name.Trim(), StringComparison.OrdinalIgnoreCase)).ToList();
                if (foundList.Count > 0)
                {
                    game.SourceId = foundList[0].Id;
                }
                else
                {
                    PlayniteApi.Database.Sources.Add(source);
                    game.SourceId = source.Id;
                }
            }
        }
    }
}
